package com.leapp.sk.util.im;

import android.media.MediaRecorder;
import android.os.SystemClock;
import com.hyphenate.util.PathUtil;
import com.leapp.sk.util.im.listener.LKVoiceRecorderListener;

import java.io.File;
import cc.vv.lklibrary.log.LogOperate;

/**
 * 语音录制操作
 */
public class LKVoiceRecorder {
    /**
     * 媒体录制
     */
    private MediaRecorder mRecorder;
    /**
     * 文件后缀
     */
    private final String EXTENSION = ".amr";
    /**
     *是否正在录音
     */
    private boolean mIsRecording = false;
    /**
     *开始时间
     */
    private long mStartTime;
    /**
     *语音文件路径
     */
    private String mVoiceFilePath = null;
    /**
     * 语音文件名称
     */
    private String mVoiceFileName = null;
    /**
     * 语音文件
     */
    private File mVoiceFile;
    /**
     *录音状态监听
     */
    private LKVoiceRecorderListener mListener;

    public LKVoiceRecorder(LKVoiceRecorderListener listener) {
        this.mListener = listener;
    }

    /**
     * 开始录制语音文件
     */
    public String startRecording() {
        String filePath = null;
        mVoiceFile = null;
        try {// 每次都需要创建mRecorder,否则,会有异常时从setOutputFile试图重用
            if (mRecorder != null) {
                mRecorder.release();
                mRecorder = null;
            }
            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
            //指定Audio编码方式，目前只有AMR_NB格式
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            // MONO
            mRecorder.setAudioChannels(1);
            // 8000Hz
            mRecorder.setAudioSamplingRate(8000);
            mRecorder.setAudioEncodingBitRate(64);
            mVoiceFileName = getVoiceFileName("voice");
            mVoiceFilePath = PathUtil.getInstance().getVoicePath() + "/" + mVoiceFileName;
            mVoiceFile = new File(mVoiceFilePath);
            mRecorder.setOutputFile(mVoiceFile.getAbsolutePath());
            mRecorder.prepare();
            mIsRecording = true;
            mRecorder.start();
            mStartTime = System.currentTimeMillis();
            new Thread(new Runnable() {//通知当前总秒数
                @Override
                public void run() {
                    int currentSeconds = 0;
                    while (mIsRecording) {
                        SystemClock.sleep(1000);
                        currentSeconds = currentSeconds + 1;
                        mListener.voiceLength(currentSeconds);
                    }
                }
            }).start();
            new Thread(new Runnable() {//通知振幅
                @Override
                public void run() {
                    try {
                        while (mIsRecording) {
                            mListener.amplitude(mRecorder.getMaxAmplitude() * 13 / 0x7FFF);
                            SystemClock.sleep(100);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            filePath = mVoiceFile == null ? null : mVoiceFile.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            LogOperate.e("录音异常===" + e.toString());
            //通知没有权限并关闭弹窗
            mListener.noPermission();
            discardRecording();
        }
        return filePath;
    }

    /**
     * 停止录音并删除录音记录
     */
    public void discardRecording() {
        if (mRecorder != null) {
            try {
                mRecorder.stop();
                mRecorder.release();
                mRecorder = null;
                deleteFile(mVoiceFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mIsRecording = false;
        }
    }

    /**
     * 删除语音文件
     *
     * @param voiceFile
     */
    public void deleteFile(File voiceFile) {
        if (voiceFile != null && voiceFile.exists() && !voiceFile.isDirectory()) {
            voiceFile.delete();
        }
    }


    /**
     * 停止录音
     *
     * @return
     */
    public void stopRecoding() {
        if (mRecorder != null) {
            mIsRecording = false;
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;
            if (mVoiceFile == null || !mVoiceFile.exists() || !mVoiceFile.isFile()) {
                mListener.recordFail();
                return;
            }
            if (mVoiceFile != null && mVoiceFile.length() == 0) {
                mVoiceFile.delete();
                mListener.recordFail();
                return;
            }
            int seconds = (int) (System.currentTimeMillis() - mStartTime) / 1000;
            mListener.stopRecording(seconds, mVoiceFilePath, mVoiceFileName, mVoiceFile);
        } else {
            mListener.recordFail();
        }
    }

    private String getVoiceFileName(String uid) {
     String now=  System.currentTimeMillis()+"";
        return uid + now+ EXTENSION;
    }

    /**
     * 判断是否正在录音
     *
     * @return
     */
    public boolean isRecording() {
        return mIsRecording;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        if (mRecorder != null) {
            mRecorder.release();
        }
    }
}
